<template>
	<section>
		<el-row>
			<!--工具条-->
			<el-col :span="23" class="toolbar toolMarginTop" id="serachId">
				<el-form :inline="true" :model="filters">
					<el-button type="primary" @click="roleAdd" size="small" style="float:left;">新增角色</el-button>
					<el-form-item style="float:right">
						<el-button type="primary" size="small" v-on:click="getList">查询</el-button>
					</el-form-item>
					<el-form-item style="float:right">
						<el-input v-model="filters.roleName" size="small" placeholder="请输入角色名称" @keyup.enter.native="searchEnterFun"></el-input>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>
		<el-row class="tac ">
			<el-col :span="23" class="titleLineSymbolTwo">
				<!--列表-->
				<el-table :data="tableData" highlight-current-row v-loading="listLoading" style="width: 100%;">
					<el-table-column type="index" label="序号" width="60">
					</el-table-column>
					<el-table-column prop="roleName" label="角色名称">
					</el-table-column>
					<el-table-column prop="type" label="类型" :formatter="formatType">
					</el-table-column>
					<!-- <el-table-column prop="isDefault" label="是否默认角色" width="120" :formatter="formatIs">
                    </el-table-column> -->
					<!-- <el-table-column prop="description" label="描述" min-width="120">
                    </el-table-column> -->
					<!-- <el-table-column prop="isDeleted" label="是否删除" min-width="120" :formatter="formatIs">
                    </el-table-column> -->
					<el-table-column prop="createdByUserName" label="创建人">
					</el-table-column>
					<el-table-column prop="createdDate" label="创建时间" min-width="155" :formatter="formatCreateDate">
					</el-table-column>
					<!-- <el-table-column prop="lastUpdatedDate" label="最后更新时间" min-width="155" :formatter="formatLastUpdateDate">
                    </el-table-column> -->
					<el-table-column label="操作" width="150" >
                        <template slot-scope="scope">
									<el-button type="text" size="small" @click="roleEdit(scope.$index, scope.row)">修改</el-button>
									<el-button type="text" size="small" @click="authEdit(scope.$index, scope.row)" >授权管理</el-button>
                                    <el-button type="text" size="small" @click="roleDelete(scope.$index, scope.row)">删除</el-button>
						</template>
						<!-- <template scope="scope">
							<el-button type="text" size="mini" @click="roleEdit(scope.$index, scope.row)" v-show="scope.row.isDefault != 1">修改</el-button>
							<!-- <el-button type="text" size="small" @click="authEdit(scope.$index, scope.row)" v-show="scope.row.isDefault != 1">授权管理</el-button> -->
							<!-- <el-button type="text" size="mini" @click="roleDelete(scope.$index, scope.row)" v-show="scope.row.isDefault != 1">删除</el-button>
						</template> --> 
					</el-table-column>
				</el-table>
			</el-col>
			<!--工具条-->
			<el-col :span="23" class="toolbar marginTop10px">
				<el-pagination layout="total, prev, pager, next, jumper" @current-change="handleCurrentPageChange"
							   :current-page="pageNum" :page-size="pageSize" :total="total">
				</el-pagination>
			</el-col>
		</el-row>
		<!-- <el-row type="flex" class="row-bg" justify="end">
            <el-pagination layout="total, prev, pager, next, jumper" @current-change="handleCurrentPageChange"
                            :current-page="pageNum" :page-size="pageSize" :total="total">
            </el-pagination>
        </el-row> -->


			<!--编辑界面-->
			<!-- <el-dialog title="角色编辑" :visible.sync="editFormVisible" :modal-append-to-body="false"> -->
			<Modal v-model="editFormVisible" title="角色编辑" width='50%'>
				<el-card>
				<el-form :model="editForm" label-width="120px" ref="editForm">
					<el-row>
						<el-col :span="12">
							<el-form-item label="角色名称">
								<el-input v-model="editForm.roleName" placeholder="不能超过20个汉字"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="角色编码">
								<el-input v-model="editForm.serialNo" :disabled="true" placeholder="系统自动生成"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="12">
							<el-form-item label="排序">
								<el-input v-model="editForm.sort"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<!-- <el-row>
						<el-col :span="12">
							<el-form-item label="角色类型">
								<el-select v-model="editForm.type" placeholder="角色类型">
									<el-option label="管理类型" value="0"></el-option>
									<el-option label="混合类" value="1"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row> -->
					<el-form-item label="描述说明">
						<el-input v-model="editForm.description"></el-input>
					</el-form-item>
				</el-form>
				</el-card>
				<div slot="footer" class="dialog-footer">
					<el-button @click.native="editFormVisible = false">取消</el-button>
					<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
				</div>
			</Modal>
			<!-- </el-dialog> -->

			<!--授权管理界面-->
			<Modal v-model="authFormVisible"  title="授权管理界面" width='50%'>
				<!-- <el-card class="treeCard">
				<el-select
						v-model="onesRolePermissionsIDS"
						multiple
						collapse-tags
						style="margin-left: 20px;"
						placeholder="请选择">
					<el-option
							v-for="item in allPermissions"
							:key="item.id"
							:label="item.title"
							:value="item.id">
					</el-option>
				</el-select>
				</el-card> -->
                <el-tree
                    :data="permissionsTree"
                    ref="tree"
                    show-checkbox
                    node-key="id"
                    check-strictly
                    :default-expanded-keys="[2]"
                    :default-checked-keys="permissionCheckedId"
                    :props="defaultProps">
                </el-tree>
				<div slot="footer" class="dialog-footer">
					<el-button @click.native="authFormVisible = false">取消</el-button>
					<el-button type="primary" @click.native="authSubmit" >提交</el-button>
				</div>
			</Modal>
			<!-- </el-dialog> -->

		<!--新增界面-->
		<!-- <el-dialog title="角色注册" :visible.sync="addFormVisible" :modal-append-to-body="false"> -->
		<Modal v-model="addFormVisible" title="新增角色" width='50%'>
			<el-card>
				<el-form :model="addForm" label-width="120px" ref="addForm">
					<el-row>
						<el-col :span="12">
							<el-form-item label="角色名称">
								<el-input v-model="addForm.roleName" placeholder="不能超过20个汉字"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="角色编码">
								<el-input v-model="addForm.serialNo" :disabled="true" placeholder="系统自动生成"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="12">
							<el-form-item label="排序">
								<el-input v-model="addForm.sort"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<!-- <el-row>
						<el-col :span="12">
							<el-form-item label="角色类型">
								<el-select v-model="addForm.type" placeholder="角色类型">
									<el-option label="管理类型" value="0"></el-option>
									<el-option label="混合类" value="1"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row> -->
					<el-form-item label="描述说明">
						<el-input type="textarea" v-model="addForm.description"></el-input>
					</el-form-item>
				</el-form>
			</el-card>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</Modal>
		<!-- </el-dialog> -->
	</section>
</template>

<script>

    import util from '../../app-market/api/util';
    //import NProgress from 'nprogress'
    import { getRoleList,addRole,editRole,
        deleteRole,searchPermission,getRolePermissions,
        addPermissionsForRole,searchRolePermissionTree } from '../../api/api';

    export default {
        data() {
            return {
                filters: {
                    roleNmae: ''
                },
                tableData: [],
                total: 0,
                pageNum: 1,
                pageSize:10,
                listLoading: false,

                allPermissions: [],// 所有的权限资源列表
                onesRolePermissions: [],// 当前角色的权限列表
                onesRolePermissionsIDS: [],// 当前角色的的权限 ID 列表
                authFormVisible: false, // 控制授权页面是否显示
                authFormCurrRoleID: 0,// 授权表单当前role ID

                editFormVisible: false,//编辑界面是否显示
                editLoading: false,
                //编辑界面数据
                editForm: {
                    roleName:'',
                    serialNo: '',
                    type: '',
                    isDefault: -1,
                    description: '',
                    isDeleted: -1,
                    sysId: -1,
                    sort: 100,
                },

                addFormVisible: false,//新增界面是否显示
                addLoading: false,
                //新增界面数据
                addForm: {
                    roleName:'',
                    serialNo: '',
                    type: '',
                    isDefault: -1,
                    description: '',
                    isDeleted: -1,
                    sysId: -1,
                    sort: 100,
                },
                permissionsTree: [],
                defaultProps: {
                  children: 'children',
                  label: 'title'
                },
                permissionCheckedId: [],

            }
        },
        methods: {
            authSubmit: function () {  // 提交资源授权信息
                console.log(this.$refs.tree.getCheckedKeys())
                var param = this.$refs.tree.getCheckedKeys()
                if(this.onesRolePermissionsIDS){
                    var params = {"roleId": this.authFormCurrRoleID,"permissionIds":param};
                    addPermissionsForRole(params).then(function(result){// 获取某个角色的权限
                        console.log(result)
                    }.bind(this)).catch(function (error) {
                        console.log(error);
                    }.bind(this));
                }else{
                    this.$message.warning('系统异常 ');
                }
                this.authFormVisible=false;
            },
            doGetRolePermissions: function (roleId) {// 获取某个角色的权限
                this.authFormCurrRoleID = roleId;
                console.log(roleId);
                getRolePermissions(roleId).then(function(result){// 获取某个角色的权限
                    console.log(roleId)
                    this.onesRolePermissions = result.data.data;
                    for (let permiss of this.onesRolePermissions) {
                        this.onesRolePermissionsIDS.push(permiss.id);
                        this.permissionCheckedId.push(permiss.id);
                    }
                    console.log("permissionCheckedId")
                    console.log(this.permissionCheckedId)
                    console.log(this.onesRolePermissions);
                    this.$refs.tree.setCheckedKeys(this.permissionCheckedId)
                }.bind(this)).catch(function (error) {
                    console.log(error);
                }.bind(this));
            },
            searchAllPermission: function (params) {
                searchPermission(params).then(function(result){// 暂时用作获取所有权限列表, 不分页
                    console.log(">>>>>>>>>>>>>>>>???????????????????")
                    console.log(result)
                    console.log(">>>>>>>>>>>>>>>>???????????????????")
                    this.allPermissions = result.data.data;
                    console.log(this.allPermissions);
                }.bind(this)).catch(function (error) {
                    console.log(error);
                }.bind(this));
            },
            formatCreateDate: function (row, column) {
                return row.createdDate = (!row.createdDate || row.createdDate == '') ? '' : util.formatDate.format(new Date(row.createdDate), 'yyyy-MM-dd hh:mm:ss');
            },
            formatLastUpdateDate: function (row, column) {
                return row.lastUpdatedDate = (!row.lastUpdatedDate || row.lastUpdatedDate == '') ? '' : util.formatDate.format(new Date(row.lastUpdatedDate), 'yyyy-MM-dd hh:mm:ss');
            },
            formatIs: function (row, column) {
                let propVal = row[column.property];
                if (column.property === 'isDefault' || column.property === 'isDeleted'){
                    return propVal == 1 ? '是' : propVal == 0  ? '否' : '未知';
                }
            },
            formatType: function (row, column) {
                if(row.type == 0){
                    return "管理类型";
                }else if(row.type == 1){
                    return "混合类";
                }else{
                    return "未知";
                }
            },
            handleCurrentPageChange: function (pageNum) {// 翻页动作
                this.pageNum = pageNum;
                this.getList();// 翻页后刷新页面数据
            },
             //实现回车键搜索功能
			searchEnterFun:function(e){
				this.getList();
            },
            //获取列表
            getList() {
                let params = {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    roleName: this.filters.roleName
                };
                this.listLoading = true;
                //NProgress.start();
                getRoleList(params).then(function(result){
                    this.tableData = result.data.data.list;
                    this.pageNum = result.data.data.pageNum;
                    this.pageSize = result.data.data.pageSize;
                    this.total = result.data.data.total;
                    this.listLoading = false;
                }.bind(this)).catch(function (error) {
                    this.listLoading = false;
                    console.log(error);
                }.bind(this));
            },
            //删除
            roleDelete: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    deleteRole(row.id).then((res) => {
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getList();
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //显示编辑界面
            roleEdit: function (index, row) {
                this.editFormVisible = true;
                this.editForm = Object.assign({}, row);
            },
            // 授权编辑
            authEdit(index, row) {
                this.authFormVisible = true;
                console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
                console.log(row)
                console.log(row.id)
                console.log(row.roleName)
                // this.onesRolePermissionsIDS = []
                this.permissionCheckedId = [];
                console.log(this.permissionCheckedId);
                this.onesRolePermissions = this.doGetRolePermissions(row.id);

            },
            //显示新增界面
            roleAdd: function () {
                this.addFormVisible = true;
                this.addForm = {
                    roleName:'',
                    serialNo: '',
                    type: '',
                    isDefault: -1,
                    description: '',
                    isDeleted: -1,
                    sysId: -1,
                    sort: 100,
                }
            },
            //编辑
            editSubmit: function () {
                if(this.editForm.roleName.length>20){
                    this.$message({
                        message: '不能超过20个汉字',
                        type: 'info'
                    });
                    return;
                }
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            //NProgress.start();
                            let params = Object.assign({}, this.editForm);
                            //格式化提交的创建时间与更新时间
                            if(params.createdDate != ''){
                                params.createdDate = Date.parse(new Date(params.createdDate));
                            }
                            if(params.updateDate != ''){
                                params.lastUpdatedDate = Date.parse(new Date(params.lastUpdatedDate));
                            }
                            editRole(params).then((res) => {
                                this.editLoading = false;
                                //NProgress.done();
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['editForm'].resetFields();
                                this.editFormVisible = false;
                                this.getList();
                            });
                        });
                    }
                });
            },
            //新增
            addSubmit: function () {
                if(this.addForm.roleName.length>20){
                    this.$message({
                        message: '不能超过20个汉字',
                        type: 'info'
                    });
                    return;
                }
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            //NProgress.start();
                            let params = Object.assign({}, this.addForm);
                            addRole(params).then((res) => {
                                this.addLoading = false;
                                //NProgress.done();
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['addForm'].resetFields();
                                this.addFormVisible = false;
                                this.getList();
                            });
                        });
                    }
                });
            },
        },
        mounted() {
            this.getList();
            this.searchAllPermission({"isPageAble":false});
            var _this = this;
            searchRolePermissionTree({}).then(function(res){
                if(res.data.code=="S100101"){
                    _this.permissionsTree = res.data.data;
                }
            });
        },
        watch: {
            getCheckedKeys:{
                handler(newVal){
                    console.log('jian'+newVal)
                }
            },
            deep: true
        }
    }

</script>
